//
//  ZJHongBaoVC.m
//  这家测试项目
//
//  Created by IOS_DEVELOPER on 2017/7/13.
//  Copyright © 2017年 陈志凌. All rights reserved.
//

#import "ZJHongBaoVC.h"
#import "XHRadarView.h"
#import "MMPulseView.h"
#import "ZJHongBaoJieguoVC.h"
#import "JKCountDownLable.h"
#import "ZJHongbaoTimeVC.h"
#import "SGAnimation.h"
#import "ZJHongBaoShuoMingVC.h"
#import "LocationManager.h"
#import "locationGPS.h"

@interface ZJHongBaoVC ()<XHRadarViewDataSource, XHRadarViewDelegate,ZJHongbaoTimeVCDelegate>{

    double longitudeLabel;/**< 经度 */
    double latitudeLabel;/**< 纬度 */
}
@property (strong, nonatomic) XHRadarView *radarView;
@property (nonatomic, strong) NSArray *pointsArray;
@property (strong, nonatomic) NSMutableArray * imgArr;
@property (weak, nonatomic) IBOutlet UILabel *money_packageLabel;
@property (weak, nonatomic) IBOutlet JKCountDownLable *NSTimeLabel;
@property (strong, nonatomic) ZJUserModel * model;
@property (strong, nonatomic) NSDictionary * dataDic;
@property (strong, nonatomic) NSDictionary * userDataDic;
@property (strong, nonatomic) NSArray * dataArr;
@property (strong, nonatomic)UIAlertController *alertController;
@property (nonatomic, strong) LocationManager *manager;
@property (strong, nonatomic) UIButton *avatarView;
@end

@implementation ZJHongBaoVC

- (LocationManager *)manager{
    
    if (!_manager) {
        _manager = [[LocationManager alloc] init];
    }
    return _manager;
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    
    UIButton *avatarView = [[UIButton alloc] init];
    avatarView.size = CGSizeMake(SCREEN_WIDTH/3.6, SCREEN_WIDTH/3.6);
    avatarView.center = self.radarView.center;
    avatarView.layer.cornerRadius = SCREEN_WIDTH/3.6/2;
    avatarView.layer.masksToBounds = YES;
    avatarView.userInteractionEnabled = NO;
    [avatarView setBackgroundColor:[UIColor redColor]];
    [avatarView setBackgroundImage:[UIImage imageNamed:@"qhb_bat_disabled"] forState:0];
    [avatarView addTarget:self action:@selector(startChange) forControlEvents:UIControlEventTouchUpInside];
    
    _avatarView = avatarView;
    MMPulseView *pulseView = [MMPulseView new];
    
    UIButton * smBtn = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 163)/2, SCREEN_HEIGHT - 76, 163, 42.5)];
    smBtn.layer.masksToBounds = YES;
    smBtn.layer.cornerRadius = 6.0f;
    [smBtn setTitle:@"红包说明" forState:0];
    [smBtn setTitleColor:RGB(132, 71, 198) forState:0];
    [smBtn setBackgroundColor:RGB(91, 32, 150)];
    [smBtn addTarget:self action:@selector(smBtn) forControlEvents:UIControlEventTouchUpInside];
    
    
    pulseView.size = CGSizeMake((SCREEN_WIDTH)/3 + 15, (SCREEN_HEIGHT)/3);
    pulseView.center = self.radarView.center;
    pulseView.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    pulseView.colors = @[(__bridge id)RGB(247, 247, 247).CGColor, (__bridge id)RGB(247, 247, 247).CGColor];
    pulseView.startPoint = CGPointMake(0, 0.5);
    pulseView.endPoint = CGPointMake(1, 0.5);
    
    pulseView.minRadius = 0;
    pulseView.maxRadius = avatarView.width/1.6;
    
    pulseView.duration = 1.5;
    pulseView.count = 3;
    pulseView.lineWidth = 15.0f;
    
    [self.radarView addSubview:pulseView];
    [self.radarView addSubview:smBtn];
    [self.radarView addSubview:avatarView];
    [self.radarView bringSubviewToFront:avatarView];
    
    [pulseView startAnimation];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(8, 25, 30, 30)];
    [backBtn setImage:[UIImage imageNamed:@"nav_icon_fh"] forState:0];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.radarView addSubview:backBtn];
    
    self.model = GET_USERINFO;
    self.money_packageLabel.text = self.model.money_package;
    self.NSTimeLabel.text = @"未开始";
    
    [self sendRequest];
}

-(void)startChange{
    
    CLLocation *orig=[[CLLocation alloc] initWithLatitude:latitudeLabel  longitude:longitudeLabel];
    CLLocation* dist=[[CLLocation alloc] initWithLatitude:[self.dataDic[@"latitude"] doubleValue] longitude:[self.dataDic[@"longitude"] doubleValue] ];
    
    CLLocationDistance kilometers=[orig distanceFromLocation:dist]/1000;
    NSLog(@"距离:%.2f",kilometers);
    
    if ([self.dataDic[@"latitude"] doubleValue] == 0) {
        
        if (self.dataDic) {
            
            [self clickHB];
            
        }else{
            ZJHongbaoTimeVC * vc = [[ZJHongbaoTimeVC alloc]init];
            vc.titleLabel.hidden = YES;
            vc.endTitle.hidden = NO;
            vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            [self presentViewController:vc animated:YES completion:nil];
        }
    }else {
    
        if (kilometers > [self.dataDic[@"range"] floatValue]) {
            self.alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前未在活动范围内" preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:_alertController animated:YES completion:nil];
            
            [self performSelector:@selector(hide) withObject:self afterDelay:2.5];
            
        }else{
        
            [self clickHB];
        }

    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.imgArr = [NSMutableArray new];
    
    locationGPS *loc = [locationGPS sharedlocationGPS];
    [loc getAuthorization]; // 授权
    [loc startLocation];
    loc.locationCompleteBlock = ^(double longitude, double latitude) {
        longitudeLabel = longitude;
        latitudeLabel = latitude;
    };
    

    XHRadarView *radarView = [[XHRadarView alloc] initWithFrame:self.view.bounds];
    radarView.frame = [UIScreen mainScreen].bounds;
    radarView.radius = SCREEN_WIDTH / 2;
    radarView.backgroundColor = [UIColor clearColor];
    radarView.dataSource = self;
    radarView.delegate = self;
    [self.view addSubview:radarView];
    
    _radarView = radarView;
    //目标点位置
    //目标点位置
    _pointsArray = @[
                     @[@-6, @120],
                     @[@-180, @128],
                     @[@80, @151],
                     @[@25, @184],
                     @[@-55, @130],
                     @[@-150, @175],
                     ];
    
    
}
-(void)sendRequest{

    NSDictionary *parameter = [LRNetwork requestParameter:@{}];
    NSString *url = [LRNetwork requestURL:@"cgi/lucky_package.php"];
    
    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
        
        self.dataDic = returnValue[@"lucky_pacage"];
        self.userDataDic = returnValue[@"user"];
        NSString * current_time = [Utils get_time:self.dataDic[@"current_time"]];
        NSLog(@"当前服务器时间:%@",current_time);
        NSString * start_time = [Utils get_time:self.dataDic[@"start_time"]];
        NSLog(@"开始时间:%@",start_time);
        NSString * end_time = [Utils get_time:self.dataDic[@"end_time"]];
        NSLog(@"结束时间:%@",end_time);
        
        if ([self.dataDic[@"is_single"] isEqualToString:@"1"] && [self.userDataDic[@"money"] doubleValue] > 0) {
            self.alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前活动只能抢一次红包哦~" preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:_alertController animated:YES completion:nil];
            
            [self performSelector:@selector(hide) withObject:self afterDelay:2.5];
            
            [self.avatarView setBackgroundImage:[UIImage imageNamed:@"qhb_bat_disabled"] forState:0];
            self.avatarView.userInteractionEnabled = NO;
            
        }else{
        
            [self.avatarView setBackgroundImage:[UIImage imageNamed:@"qhb_bat_qq"] forState:0];
            self.avatarView.userInteractionEnabled = YES;
        }
        
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
        
        ZJHongbaoTimeVC * vc = [[ZJHongbaoTimeVC alloc]init];
        vc.titleLabel.hidden = YES;
        vc.endTitle.hidden = NO;
        vc.delegate = self;
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [self presentViewController:vc animated:YES completion:nil];
 
    } withFailureBlock:^{
        
    }];

}
-(void)backRoot{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self dismissViewControllerAnimated:YES completion:nil];
    });
}
-(void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Custom Methods
- (void)startUpdatingRadar {
    typeof(self) __weak weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.radarView show];
    });
}

#pragma mark - XHRadarViewDataSource
- (NSInteger)numberOfSectionsInRadarView:(XHRadarView *)radarView {
    return 3;
}
- (NSInteger)numberOfPointsInRadarView:(XHRadarView *)radarView {
    return [self.dataArr count];
}
//自定义目标点视图

- (UIView *)radarView:(XHRadarView *)radarView viewForIndex:(NSUInteger)index {
    UIView *pointView ;
    //    pointView.backgroundColor = [UIColor redColor];
    
    UIImageView *imageView;
    
    UIImageView * imgV = [[UIImageView alloc]init];

        pointView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/10.7 + 15, SCREEN_WIDTH/8 + 15)];
        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(7.5, 7.5, SCREEN_WIDTH/10.7 , SCREEN_WIDTH/8)];
        
        [imageView setImage:[UIImage imageNamed:@"qhb_icon_x"]];
         [pointView addSubview:imageView];

    
    [self.avatarView setBackgroundImage:[UIImage imageNamed:@"qhb_bat_disabled"] forState:0];
    self.avatarView.userInteractionEnabled = NO;
    [self.imgArr addObject:imgV];
    return pointView;
}

//目标点所在位置

- (CGPoint)radarView:(XHRadarView *)radarView positionForIndex:(NSUInteger)index {
    NSArray *point = [self.pointsArray objectAtIndex:index];
    return CGPointMake([point[0] floatValue], [point[1] floatValue]);
}

#pragma mark - XHRadarViewDelegate

//点击事件

- (void)radarView:(XHRadarView *)radarView didSelectItemAtIndex:(NSUInteger)index {
    NSLog(@"didSelectItemAtIndex:%lu", (unsigned long)index);
        
        [HUD showLoading:@"拼抢中..."];
        NSDictionary * dic = self.dataArr[index];
        NSDictionary *parameter = [LRNetwork requestParameter:@{@"package_id":self.dataDic[@"package_id"],
                                                                @"code":dic[@"code"]}];
        NSString *url = [LRNetwork requestURL:@"cgi/lucky_package_acquire.php"];
        typeof(self) __weak weakSelf = self;
        [weakSelf.radarView hide];
        
        [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
            
            ZJHongBaoJieguoVC * vc = [[ZJHongBaoJieguoVC alloc]init];
            vc.isBig = NO;
            vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            if (![returnValue[@"money"] isEqualToString:@"0"]) {
                vc.moneyStr = returnValue[@"money"];
                
                self.model.money_package = [NSString stringWithFormat:@"%.2f",[self.model.money_package floatValue] + [returnValue[@"money"] floatValue]];
                self.model.money_total = [NSString stringWithFormat:@"%.2f",[self.model.money_total floatValue] + [returnValue[@"money"] floatValue]];
                SYN_USER(self.model);
                self.money_packageLabel.text = self.model.money_package;
                
            }
                
                NSMutableArray * arr = [[NSMutableArray alloc]init];
                [arr addObjectsFromArray:self.dataArr];
                
                for (NSDictionary * dict in self.dataArr) {
                        [arr removeObject:dict];
                }
                
                self.dataArr = arr;
                [self.radarView show];

             [self sendRequest];
            [self presentViewController:vc animated:YES completion:nil];
            [HUD hide];
        } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
            [HUD showErrorMsg:errorMessage];
        } withFailureBlock:^{
            
        }];
    
    if ([self.dataDic[@"is_single"] isEqualToString:@"1"] && [self.userDataDic[@"money"] doubleValue] > 0) {
        self.alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前活动只能抢一次红包哦~" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:_alertController animated:YES completion:nil];
        
        [self performSelector:@selector(hide) withObject:self afterDelay:2.5];
        
        [self.avatarView setBackgroundImage:[UIImage imageNamed:@"qhb_bat_disabled"] forState:0];
        self.avatarView.userInteractionEnabled = NO;
        
    }else{

    [self.avatarView setBackgroundImage:[UIImage imageNamed:@"qhb_bat_qq"] forState:0];

    self.avatarView.userInteractionEnabled = YES;
        
    }
 
}

-(void)clickHB{

    //当前服务器时间
    //        NSDate * severDate = [self Get_timeForDate:self.dataDic[@"current_time"]];
    //开始时间
    NSDate * startDate = [Utils Get_timeForDate:self.dataDic[@"start_time"]];
    //结束时间
    NSDate * endDate = [Utils Get_timeForDate:self.dataDic[@"end_time"]];
    
    //系统当前时间
    NSDate *nowDate = [Utils getInternetDate];
    
    NSInteger startResult = [Utils compareOneDay:nowDate withAnotherDay:startDate];
    
    NSInteger endResult = [Utils compareOneDay:nowDate withAnotherDay:endDate];
    
    if ((startResult == 0 || startResult == 1) && endResult == -1) {
        
        //时间计算
        NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
        
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设定时间格式,这里可以设置成自己需要的格式
        
        //最后抢红包时间
        
        dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSTimeZone *zone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
        NSDate *localeDate =[dateFormat dateFromString:self.userDataDic[@"last"]];
        NSInteger intervalLast = [zone secondsFromGMTForDate: localeDate];
        NSDate *lastDate = [localeDate  dateByAddingTimeInterval: intervalLast];
        
        //间隔时间
        NSTimeInterval  interval = [self.dataDic[@"interval"] integerValue];
        
        //下次抢红包时间
        NSDate *date1 = [NSDate dateWithTimeInterval:interval sinceDate:lastDate];
        
        //间隔时间比较
        NSInteger result1 = [Utils compareOneDay:nowDate withAnotherDay:date1];
        
        if (result1 ==0 || result1 == 1) {
            //                self.radarView.labelText = @"搜索中...";
            NSDictionary *parameter = [LRNetwork requestParameter:@{@"package_id":self.dataDic[@"package_id"]}];
            NSString *url = [LRNetwork requestURL:@"cgi/lucky_package_get.php"];
            
            [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
                
                self.dataArr = returnValue[@"package"];
                
                if (self.dataArr.count < 1) {
                    [HUD showMsg:@"暂时无红包可抢~"];
                    
                }else{
                    NSDictionary * dict = self.dataArr[0];
                    
                    if ([dict[@"big"] isEqualToString:@"1"]) {
                        
                        SGActivePopupsView *APView = [[SGActivePopupsView alloc] init];
                        APView.imageName = [UIImage imageNamed:@"qhb_dhb"];
                        
                        APView.selectedImageBlock = ^{
                            [HUD showLoading:@"拼抢中..."];
                            NSDictionary * dic = self.dataArr[0];
                            NSDictionary *parameter = [LRNetwork requestParameter:@{@"package_id":self.dataDic[@"package_id"],
                                                                                    @"code":dic[@"code"]}];
                            NSString *url = [LRNetwork requestURL:@"cgi/lucky_package_acquire.php"];
                            typeof(self) __weak weakSelf = self;
                            [weakSelf.radarView hide];
                            
                            [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
                                
                                ZJHongBaoJieguoVC * vc = [[ZJHongBaoJieguoVC alloc]init];
                                vc.isBig = YES;
                                vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                                if (![returnValue[@"money"] isEqualToString:@"0"]) {
                                    vc.moneyStr = returnValue[@"money"];
                                    
                                    self.model.money_package = [NSString stringWithFormat:@"%.2f",[self.model.money_package floatValue] + [returnValue[@"money"] floatValue]];
                                    self.model.money_total = [NSString stringWithFormat:@"%.2f",[self.model.money_total floatValue] + [returnValue[@"money"] floatValue]];
                                    SYN_USER(self.model);
                                    self.money_packageLabel.text = self.model.money_package;
                                    
                                }
                                
                                [self sendRequest];
                                [self presentViewController:vc animated:YES completion:nil];
                                [HUD hide];
                            } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
                                [HUD showErrorMsg:errorMessage];
                            } withFailureBlock:^{
                                
                            }];
                        };
                        [APView SG_show];
                        
                    }
                    else{
                        
                        [self startUpdatingRadar];
                        
                    }
                    
                }
                
            } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
                [HUD showErrorMsg:errorMessage];
            } withFailureBlock:^{
                
            }];
            
        }else{
            
            ZJHongbaoTimeVC * vc = [[ZJHongbaoTimeVC alloc]init];
            vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            vc.dateStr = date1;
            [self presentViewController:vc animated:YES completion:nil];
        }
        
    }else{
        
        ZJHongbaoTimeVC * vc = [[ZJHongbaoTimeVC alloc]init];
        vc.titleLabel.hidden = YES;
        vc.endTitle.hidden = NO;
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [self presentViewController:vc animated:YES completion:nil];
    }
}

-(void)smBtn{
    ZJHongBaoShuoMingVC *vc = [[ZJHongBaoShuoMingVC alloc]init];
    [self presentSemiViewController:vc];
}

-(void)hide{
    
    [self.alertController dismissViewControllerAnimated:YES completion:nil];
    
}
@end
